<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Dubbo Cluster | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="clusterCluster 将 Directory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个. 集群模块处于服务提供者和消费者之间,对于服务消费者来说,集群可向其屏蔽服务提供者集群的情况,使其能够专心进行远程调用. cluster 继承结构 12345678910Cluster(com.alibaba.dubbo.rpc.c">
<meta property="og:type" content="article">
<meta property="og:title" content="Dubbo Cluster">
<meta property="og:url" content="https://flyingzc.github.io/articles/dubbo/dubbo05-cluster.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="clusterCluster 将 Directory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个. 集群模块处于服务提供者和消费者之间,对于服务消费者来说,集群可向其屏蔽服务提供者集群的情况,使其能够专心进行远程调用. cluster 继承结构 12345678910Cluster(com.alibaba.dubbo.rpc.c">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2019-12-03T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.211Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Dubbo">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Dubbo Cluster",
  "url": "https://flyingzc.github.io/articles/dubbo/dubbo05-cluster.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2019-12-03T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.211Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/dubbo/dubbo05-cluster.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Dubbo Cluster',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Dubbo Cluster</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Dubbo Cluster</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-12-03T16:00:00.000Z" title="发表于 2019-12-04 00:00:00">2019-12-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.211Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Dubbo/">Dubbo</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="cluster"><a href="#cluster" class="headerlink" title="cluster"></a>cluster</h1><p>Cluster 将 Directory 中的多个 Invoker 伪装成一个 Invoker,对上层透明,伪装过程包含了容错逻辑,调用失败后,重试另一个.</p>
<p>集群模块处于服务提供者和消费者之间,对于服务消费者来说,集群可向其屏蔽服务提供者集群的情况,使其能够专心进行远程调用.</p>
<p>cluster 继承结构</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">Cluster(com.alibaba.dubbo.rpc.cluster)<br>    MergeableCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    FailfastCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    MockClusterWrapper(com.alibaba.dubbo.rpc.cluster.support.wrapper)<br>    FailsafeCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    ForkingCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    AvailableCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    FailbackCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    FailoverCluster(com.alibaba.dubbo.rpc.cluster.support)<br>    BroadcastCluster(com.alibaba.dubbo.rpc.cluster.support)<br></code></pre></td></tr></table></figure>

<p>这些 Cluster 实现类里均实现了 join() 方法,用于创建其对应的 ClusterInvoker.</p>
<h1 id="Invoker接口"><a href="#Invoker接口" class="headerlink" title="Invoker接口"></a>Invoker接口</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">Invoker(com.alibaba.dubbo.rpc)<br>    ProviderInvokerWrapper(com.alibaba.dubbo.registry.support)<br>    MockClusterInvoker(com.alibaba.dubbo.rpc.cluster.support.wrapper)<br>    AbstractProxyInvoker(com.alibaba.dubbo.rpc.proxy)<br>    ListenerInvokerWrapper(com.alibaba.dubbo.rpc.listener)<br>    DelegateInvoker(com.alibaba.dubbo.rpc.support)<br>    InvokerWrapper(com.alibaba.dubbo.rpc.protocol)<br>    AbstractClusterInvoker(com.alibaba.dubbo.rpc.cluster.support)<br>    MergeableClusterInvoker(com.alibaba.dubbo.rpc.cluster.support)<br>    AbstractInvoker(com.alibaba.dubbo.rpc.protocol)<br></code></pre></td></tr></table></figure>

<p>这些 Invoker实现类的父类 AbstractClusterInvoker.invoke() 中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"> <span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">invoke</span><span class="hljs-params">(<span class="hljs-keyword">final</span> Invocation invocation)</span> <span class="hljs-keyword">throws</span> RpcException &#123;<br>    <span class="hljs-comment">// 校验是否销毁</span><br>    checkWhetherDestroyed();<br><br>    <span class="hljs-comment">// 通过 directory 获得所有服务提供者 Invoker 集合</span><br>    List&lt;Invoker&lt;T&gt;&gt; invokers = list(invocation);<br><br>    <span class="hljs-comment">// 获得 LoadBalance 对象</span><br>    LoadBalance loadbalance;<br>    <span class="hljs-keyword">if</span> (invokers != <span class="hljs-literal">null</span> &amp;&amp; !invokers.isEmpty()) &#123;<br>        loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(<span class="hljs-number">0</span>).getUrl()<br>                .getMethodParameter(invocation.getMethodName(), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);<br>    &#125;<br><br>    <span class="hljs-comment">// 设置调用编号,若是异步调用</span><br>    RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);<br><br>    <span class="hljs-comment">// 执行调用</span><br>    <span class="hljs-keyword">return</span> doInvoke(invocation, invokers, loadbalance);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="FailoverClusterInvoker"><a href="#FailoverClusterInvoker" class="headerlink" title="FailoverClusterInvoker"></a>FailoverClusterInvoker</h2><p>FailoverClusterInvoker 的 doInvoke() 方法首先是获取重试次数,然后根据重试次数进行循环调用,失败后进行重试.</p>
<p>在 for 循环内,首先是通过 loadBalance 选择一个 Invoker,然后再通过这个 Invoker.invoke() 方法进行远程调用.如果失败了,记录下异常,并进行重试.重试时会再次调用父类的 list() 方法列举 Invoker.</p>
<h2 id="FailbackClusterInvoker"><a href="#FailbackClusterInvoker" class="headerlink" title="FailbackClusterInvoker"></a>FailbackClusterInvoker</h2><p>FailbackClusterInvoker 会在调用失败后,返回一个空结果给服务消费者.</p>
<p>并通过定时任务对失败的调用进行重传,适合执行消息通知等操作.</p>
<p>doInvoke() 逻辑:<br>1.先检查 可用的 invoker 集合是否为空,若为空,则抛出异常.<br>2.调用select()通过loadbalance选择一个invoker,并发起rpc调用.<br>3.若调用失败,则添加到 failed 这个map中,并延迟初始化定时任务每隔5秒遍历一次 failed 里的 invoker,发起调用,若调用成功则从中移除.</p>
<h2 id="FailfastClusterInvoker"><a href="#FailfastClusterInvoker" class="headerlink" title="FailfastClusterInvoker"></a>FailfastClusterInvoker</h2><p>FailfastClusterInvoker 只会进行一次调用,失败后立即抛出异常.适用于幂等操作,比如新增记录.</p>
<p>doInvoke() 逻辑:<br>1.先检查 可用的 invoker 集合是否为空,若为空,则抛出异常.<br>2.调用select()通过loadbalance选择一个invoker,并发起rpc调用.<br>3.若调用失败,则先判断异常类型 若是 RpcException 或 业务异常,直接抛出.否则包装一层 RpcException 并抛出.</p>
<h2 id="FailsafeClusterInvoker"><a href="#FailsafeClusterInvoker" class="headerlink" title="FailsafeClusterInvoker"></a>FailsafeClusterInvoker</h2><p>FailsafeClusterInvoker 是一种失败安全的 Cluster Invoker.</p>
<p>所谓的失败安全是指,当调用过程中出现异常时,FailsafeClusterInvoker 仅会打印异常,而不会抛出异常.适用于写入审计日志等操作.</p>
<p>doInvoke() 逻辑:<br>没啥好说的,调用抛异常,捕获 Throwable 异常,打印异常日志,创建 RpcResult 对象返回.</p>
<h2 id="ForkingClusterInvoker"><a href="#ForkingClusterInvoker" class="headerlink" title="ForkingClusterInvoker"></a>ForkingClusterInvoker</h2><p>ForkingClusterInvoker 会在运行时通过线程池创建多个线程,并发调用多个服务提供者.</p>
<p>只要有一个服务提供者成功返回了结果,doInvoke 方法就会立即结束运行.</p>
<p>ForkingClusterInvoker 的应用场景是在一些对实时性要求比较高读操作(注意是读操作,并行写操作可能不安全)下使用,但这将会耗费更多的资源.</p>
<p>doInvoke() 逻辑:<br>1.先检查 可用的 invoker 集合是否为空,若为空,则抛出异常.<br>2.获取并发数 forks,调用 forks 次 select()方法获得 invokers 列表<br>3.遍历 invokers, 并发调用每个 invoker.invoke(),返回结果添加到 LinkedBlockingQueue 中<br>4.main线程阻塞在 ref.poll(timeout, TimeUnit.MILLISECONDS) 上等待第一个返回结果</p>
<h2 id="BroadcastClusterInvoker"><a href="#BroadcastClusterInvoker" class="headerlink" title="BroadcastClusterInvoker"></a>BroadcastClusterInvoker</h2><p>BroadcastClusterInvoker 会逐个调用每个服务提供者,如果其中一台报错,在循环调用结束后,BroadcastClusterInvoker 会抛出异常.</p>
<p>该类通常用于通知所有提供者更新缓存或日志等本地资源信息.<br>doInvoke() 逻辑:<br>没啥好说的,循环调用 invokers,调用失败记录 exception.最后有异常就抛出.</p>
<p><a target="_blank" rel="noopener" href="http://dubbo.apache.org/zh-cn/docs/source_code_guide/cluster.html">官网cluster部分</a></p>
<h1 id="directory"><a href="#directory" class="headerlink" title="directory"></a>directory</h1><p>主要看 RegistryDirectory 的实现.</p>
<h2 id="RegistryDirectory"><a href="#RegistryDirectory" class="headerlink" title="RegistryDirectory"></a>RegistryDirectory</h2><p>RegistryDirectory 实现了 NotifyListener 接口,当注册中心节点信息发生变化后,RegistryDirectory 可以通过此接口方法得到变更信息.</p>
<p>收到变更通知后,RegistryDirectory 可根据配置变更信息刷新 Invoker 列表.</p>
<p>RegistryDirectory 中有几个比较重要的逻辑:<br>1.Invoker.doList() 逻辑<br>2.接收服务配置变更的逻辑<br>3.Invoker 列表的刷新逻辑</p>
<p>doList()逻辑:<br>没啥好说的,就是从 methodInvokerMap(即 methodInvokerMap) 缓存中获取 methodName 对应的 invokers</p>
<p>接收服务变更通知<br>RegistryDirectory 是一个动态服务目录,会随注册中心配置的变化进行动态调整.因此 RegistryDirectory 实现了 NotifyListener 接口,通过这个接口获取注册中心变更通知.</p>
<p>1.ZookeeperRegistry.doSubscribe() 订阅时会创建一个 ChildListener,当发生 childChanged 事件时,会回调它的 childChanged() 方法<br>2.调用ZookeeperRegistry.this.notify(),由于 RegistryDirectory 实现了 NotifyListener 接口,会调用 RegistryDirectory.notify()<br>3.RegistryDirectory.notify() 调用 refreshInvoker(invokerUrls);<br>将 url 转成 Invoker,得到 <code>&lt;url, Invoker&gt;</code> 的映射关系.然后进一步进行转换,得到 <code>&lt;methodName, InvokerList&gt;</code> 映射关系.之后进行多组 Invoker 合并操作,并将合并结果赋值给 methodInvokerMap.methodInvokerMap 变量在 doList 方法中会被用到,doList 会对该变量进行读操作,在这里是写操作.当新的 Invoker 列表生成后,还要一个重要的工作要做,就是销毁无用的 Invoker,避免服务消费者调用已下线的服务的服务.</p>
<p><a target="_blank" rel="noopener" href="http://dubbo.apache.org/zh-cn/docs/source_code_guide/directory.html">官网directory部分</a></p>
<h1 id="router"><a href="#router" class="headerlink" title="router"></a>router</h1><p>服务路由包含一条路由规则,路由规则决定了服务消费者的调用目标,即<code>规定了服务消费者可调用哪些服务提供者</code>.<br>比如条件路由 ConditionRouter</p>
<p>rule格式 [服务消费者匹配条件] &#x3D;&gt; [服务提供者匹配条件],比如 rule &#x3D; “host &#x3D; 2.2.2.2,1.1.1.1,3.3.3.3 &#x3D;&gt; host &#x3D; 1.2.3.4”</p>
<p>ConditionRouter 构造方法里 先是对路由规则做预处理.处理结果存入 MatchPair.matches 和 MatchPair.mismatches,分别对应 匹配 和 不匹配的条件.最后 whenCondition 保存 消费者匹配条件,thenCondition 保存 提供者地址列表的过滤条件.</p>
<p>ConditionRouter.router(): 服务路由的逻辑.<br>1.调用 matchWhen 对服务消费者进行匹配,如果匹配失败,直接返回 Invoker 列表<br>2.如果匹配成功,再对服务提供者进行匹配</p>
<p>ConditionRouterTest</p>
<p><a target="_blank" rel="noopener" href="http://dubbo.apache.org/zh-cn/docs/source_code_guide/router.html">官网router部分</a></p>
<h1 id="loadBalance"><a href="#loadBalance" class="headerlink" title="loadBalance"></a>loadBalance</h1><p><a target="_blank" rel="noopener" href="http://dubbo.apache.org/zh-cn/docs/source_code_guide/loadbalance.html">官网loadBalance部分</a><br>loadBalance 类的继承结构</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">AbstractLoadBalance (com.alibaba.dubbo.rpc.cluster.loadbalance)<br>    RoundRobinLoadBalance (com.alibaba.dubbo.rpc.cluster.loadbalance)<br>    LeastActiveLoadBalance (com.alibaba.dubbo.rpc.cluster.loadbalance)<br>    RandomLoadBalance (com.alibaba.dubbo.rpc.cluster.loadbalance)<br>    ConsistentHashLoadBalance (com.alibaba.dubbo.rpc.cluster.loadbalance)<br></code></pre></td></tr></table></figure>
<h2 id="RandomLoadBalance"><a href="#RandomLoadBalance" class="headerlink" title="RandomLoadBalance"></a>RandomLoadBalance</h2><p>按权重设置随机概率.如果所有invoker权重都相等,则随机取一个.不相等,则按照权重的比例随机取.</p>
<h2 id="LeastActiveLoadBalance"><a href="#LeastActiveLoadBalance" class="headerlink" title="LeastActiveLoadBalance"></a>LeastActiveLoadBalance</h2><p>最小活跃数负载均衡。活跃调用数越小，表明该服务提供者效率越高，单位时间内可处理更多的请求。此时应优先将请求分配给该服务提供者。</p>
<p>初始情况下，所有服务提供者活跃数均为0。每收到一个请求，活跃数加1，完成请求后则将活跃数减1。在服务运行一段时间后，性能好的服务提供者处理请求的速度更快，因此活跃数下降的也越快，此时这样的服务提供者能够优先获取到新的服务请求、这就是最小活跃数负载均衡算法的基本思想。</p>
<h2 id="ConsistentHashLoadBalance"><a href="#ConsistentHashLoadBalance" class="headerlink" title="ConsistentHashLoadBalance"></a>ConsistentHashLoadBalance</h2><p>一致性 Hash，相同参数的请求总是发到同一提供者。</p>
<p>当某一台提供者挂时，原本发往该提供者的请求，基于虚拟节点，平摊到其它提供者，不会引起剧烈变动。</p>
<h2 id="RoundRobinLoadBalance"><a href="#RoundRobinLoadBalance" class="headerlink" title="RoundRobinLoadBalance"></a>RoundRobinLoadBalance</h2><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/dubbo/dubbo05-cluster.html">https://flyingzc.github.io/articles/dubbo/dubbo05-cluster.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Dubbo/">Dubbo</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/dubbo/dubbo01-overview.html" title="Dubbo 整理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-26</div><div class="info-item-2">Dubbo 整理</div></div><div class="info-2"><div class="info-item-1">整理自官网, 对整体理解 Dubbo 很有作用. 作用Apache Dubbo 是一款高性能, 轻量级的 Java RPC 框架. 三大核心能力面向接口的远程方法调用 智能容错和负载均衡 以及服务自动注册和发现 健壮性监控中心宕掉不影响使用, 只是丢失部分采样数据. 数据库宕掉后, 注册中心仍能通过缓存提供服务列表查询, 但不能注册新服务. 注册中心对等集群, 任意一台宕掉后, 将自动切换到另一台. 注册中心全部宕掉后, 服务提供者 和 服务消费者 仍能通过本地缓存通讯. 服务提供者无状态, 任意一台宕掉后, 不影响使用. 服务提供者全部宕掉后, 服务消费者应用将无法使用, 并 无限次重连等待服务提供者恢复. 伸缩性注册中心为对等集群, 可动态增加机器部署实例, 所有客户端将自动发现新的注册中心. 服务提供者无状态, 可动态增加机器部署实例, 注册中心将推送新的服务提供者信息给消费者. 协议 Dubbo 协议采用 NIO 复用单一长连接, 并使用线程池并发处理请求, 减少握手和加大并发效率, 性能较好(推荐使用)在大文件传输时, 单一连接会成为瓶颈可用于生产环境  Rmi...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo02-spi.html" title="Dubbo SPI 机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-27</div><div class="info-item-2">Dubbo SPI 机制</div></div><div class="info-2"><div class="info-item-1">SPI 机制SPI 作用SPI 全称为 Service Provider Interface, 是一种服务发现机制. SPI 的本质是将接口实现类的全限定名配置在文件中, 并由服务加载器读取配置文件, 加载实现类. 这样可以在运行时, 动态为接口替换实现类. 正因此特性, 我们可以很容易的通过 SPI 机制为我们的程序提供拓展功能. Dubbo 里面有很多个组件, 每个组件在框架中都是以接口的形式抽象出来. 具体的实现又分很多种, 在程序执行时根据用户的配置来按需取接口的实现类. Dubbo 实现的 SPI 与 JDK 自带的 SPI 的区别摘自官网  JDK 标准的 SPI 会一次性实例化扩展点所有实现, 如果有扩展实现初始化很耗时, 但如果没用上也加载, 会很浪费资源.  如果扩展点加载失败, 连扩展点的名称都拿不到了.比如: JDK 标准的 ScriptEngine, 通过 getName() 获取脚本类型的名称, 但如果 RubyScriptEngine 因为所依赖的 jruby.jar 不存在, 导致 RubyScriptEngine 类加载失败,...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo04-refer.html" title="Dubbo 服务引用"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-29</div><div class="info-item-2">Dubbo 服务引用</div></div><div class="info-2"><div class="info-item-1">官网 客户端服务引用客户端服务引用 demo12DemoService demoService = (DemoService) context.getBean(&quot;demoService&quot;); // get remote service proxydemoService.sayHello(&quot;world&quot;); dubbo 在客户端动态的生成了一个该 Interface 类型的代理类.在这个代理类中封装了远程服务调用的组件. DemoService 创建12&lt;dubbo:reference id=&quot;demoService&quot; group=&quot;g1&quot; check=&quot;true&quot; interface=&quot;com.alibaba.dubbo.demo.DemoService&quot;                     client=&quot;netty4&quot; timeout=&quot;10000&quot; callbacks=&quot;1000&quot;...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo03-export.html" title="Dubbo 服务暴露"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-29</div><div class="info-item-2">Dubbo 服务暴露</div></div><div class="info-2"><div class="info-item-1">Dubbo 与 Spring 的结合代码在 dubbo-config 下的 dubbo-config-spring 模块中  META-INF&#x2F;dubbo.xsddubbo.xsd 定义了 dubbo 自定义标签 META-INF&#x2F;spring.schemasspring.schemas 指定了 dubbo.xsd 文件的位置. 1http\://code.alibabatech.com/schema/dubbo/dubbo.xsd=META-INF/dubbo.xsd  META-INF&#x2F;spring.handlers关联 DubboNamespaceHandler 命名空间处理器和 dubbo.xsd 中的 targetNamespace,即...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo06-provider.html" title="Dubbo Provider处理请求"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-05</div><div class="info-item-2">Dubbo Provider处理请求</div></div><div class="info-2"><div class="info-item-1">服务端接收并响应请求流程provider处理请求流程  123456789101112- NettyServerWorker线程接收请求    - ByteToMessageDecoder.channelRead()        - ByteToMessageDecoder.callDecode()            - NettyCodecAdapter.InternalDecoder.decode()                - DubboCountCodec.decode()解码        - fireChannelRead(ctx, out, size)            - NettyServerHandler.channelRead()                - AbstractPeer.received()                    - MultiMessageHandler.received()                        - HeartbeatHandler.received()            ...</div></div></div></a><a class="pagination-related" href="/articles/dubbo/dubbo07-heartbeat.html" title="Dubbo心跳机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-15</div><div class="info-item-2">Dubbo心跳机制</div></div><div class="info-2"><div class="info-item-1">Dubbo心跳机制Dubbo 默认客户端和服务端都会发送心跳报文,用来保持 TCP 长连接状态. 在客户端和服务端,Dubbo 都会开启一个线程 循环扫描 并 检测连接是否超时. 在服务端发现超时则会主动关闭客户端连接. 在客户端发现超时则会主动重新创建连接. 默认心跳检测时间是 60 秒. 原理provider 心跳默认是在 heartbeat(一分钟)内如果没有读消息或写消息,就会发送心跳请求消息,如果连着3次(180s)没有读消息,provider会关闭channel. consumer 端的心跳默认是在 一分钟 内如果没有读消息或写消息,就会发送心跳请求消息,如果连着3次(三分钟)没有读消息,consumer会进行重连. 开启定时任务provider 在启动 netty时,在 HeaderExchangeServer 的构造方法中,会通过 startHeatbeatTimer() 启动心跳定时任务.consumer 在 HeaderExchangeClient 的构造方法里,同样通过 startHeatbeatTimer()...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#cluster"><span class="toc-number">1.</span> <span class="toc-text">cluster</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Invoker%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.</span> <span class="toc-text">Invoker接口</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#FailoverClusterInvoker"><span class="toc-number">2.1.</span> <span class="toc-text">FailoverClusterInvoker</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#FailbackClusterInvoker"><span class="toc-number">2.2.</span> <span class="toc-text">FailbackClusterInvoker</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#FailfastClusterInvoker"><span class="toc-number">2.3.</span> <span class="toc-text">FailfastClusterInvoker</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#FailsafeClusterInvoker"><span class="toc-number">2.4.</span> <span class="toc-text">FailsafeClusterInvoker</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ForkingClusterInvoker"><span class="toc-number">2.5.</span> <span class="toc-text">ForkingClusterInvoker</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#BroadcastClusterInvoker"><span class="toc-number">2.6.</span> <span class="toc-text">BroadcastClusterInvoker</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#directory"><span class="toc-number">3.</span> <span class="toc-text">directory</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#RegistryDirectory"><span class="toc-number">3.1.</span> <span class="toc-text">RegistryDirectory</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#router"><span class="toc-number">4.</span> <span class="toc-text">router</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#loadBalance"><span class="toc-number">5.</span> <span class="toc-text">loadBalance</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#RandomLoadBalance"><span class="toc-number">5.1.</span> <span class="toc-text">RandomLoadBalance</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#LeastActiveLoadBalance"><span class="toc-number">5.2.</span> <span class="toc-text">LeastActiveLoadBalance</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ConsistentHashLoadBalance"><span class="toc-number">5.3.</span> <span class="toc-text">ConsistentHashLoadBalance</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RoundRobinLoadBalance"><span class="toc-number">5.4.</span> <span class="toc-text">RoundRobinLoadBalance</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>